package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author 黑虎阿福
 * @since 2022-04-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;


    /**
     * 用户登录
     *
     * @param dto
     */
    @Override
    public Map<String,Object> login(AdUserLoginDto dto) {
        //首先验证用户是否存在
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName,dto.getName());
        AdUser adUser = getOne(wrapper);
        if (adUser==null){
            //用户不存在
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //验证密码
        boolean matches = encoder.matches(dto.getPassword(), adUser.getPassword());
        if(!matches){
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(adUser.getId(), 30);
        AdUserDto adUserDto = BeanHelper.copyProperties(adUser, AdUserDto.class);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserDto);
        return map;
    }
}
